#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:do_exam1.py
# author:王雯雯
# datetime:2024-12-8
# software: PyCharm

import streamlit as st
import pymysql
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# 配置数据库连接参数（根据实际情况修改）
config = {
    'host': 'localhost',
    'user': 'root',
    'password': '12345678',
    'database': 'app_database'
}

# 创建数据库连接（使用pymysql方式）
def connect_to_database():
    try:
        connection = pymysql.connect(**config)
        return connection
    except pymysql.Error as e:
        st.error(f"数据库连接错误: {e}")
        return None

# 创建数据库连接引擎（使用sqlalchemy方式，这里以MySQL为例）
engine = create_engine('mysql+pymysql://room:12345678@localhost/app_database')

# 创建数据库会话（这里简单示例，可进一步优化会话管理）
def get_session():
    Session = sessionmaker(bind=engine)
    session = Session()
    return session

# 登录页面函数
def login_page():
    st.title("登录")
    username = st.text_input("用户名")
    password = st.text_input("密码", type="password")
    if st.button("登录"):
        connection = connect_to_database()  # 或者使用 session = get_session() 取决于你想采用的连接方式
        if connection:
            try:
                cursor = connection.cursor()  # 如果使用pymysql
                # 执行查询语句，验证用户信息
                query = "SELECT * FROM users WHERE username = %s AND password = %s"
                cursor.execute(query, (username, password))
                result = cursor.fetchone()
                if result:
                    st.success("登录成功！")
                    return True
                else:
                    st.error("用户名或密码错误，请重新输入。")
            except Exception as e:
                st.error(f"验证过程出现错误: {e}")
            finally:
                if connection:
                    connection.close()  # 如果使用pymysql，关闭连接
        else:
            st.error("无法连接数据库，请检查配置。")
    return False

# 主页函数
def main_page():
    st.title("主页")
    connection = connect_to_database()  # 或者使用 session = get_session()
    if connection:
        try:
            cursor = connection.cursor()  # 如果使用pymysql

            query = "SELECT * FROM users"
            cursor.execute(query)
            results = cursor.fetchall()
            for row in results:
                st.write(f"用户ID: {row[0]}, 用户名: {row[1]}")
        except Exception as e:
            st.error(f"获取数据出现错误: {e}")
        finally:
            if connection:
                connection.close()  # 如果使用pymysql，关闭连接
    else:
        st.error("无法连接数据库，请检查配置。")

# 主函数，控制页面切换
def main():
    page = "login"
    if "page" not in st.session_state:
        st.session_state.page = page
    if st.session_state.page == "login":
        if login_page():
            st.session_state.page = "main"
    elif st.session_state.page == "main":
        main_page()

if __name__ == "__main__":
    main()
